﻿using System;
using System.Linq;
using HarmonyLib;
using Helpers;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.CampaignBehaviors;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Extensions;
using TaleWorlds.Core;
using TaleWorlds.Library;

namespace MarriageFertility.Patches;


[HarmonyPatch(typeof(AgingCampaignBehavior), "OnHeroReachesTeenAge")]
public static class AgingCampaignBehaviorPatch
{
    public static bool Prefix(Hero hero)
    {
        // Null check for the hero parameter
        if (hero == null)
        {
            Debug.Print("AgingCampaignBehavior.OnHeroReachesTeenAge: Hero is null.");
            return false; // Skip original method
        }

        // Handle equipment assignment safely
        try
        {
            if (Campaign.Current?.Models?.EquipmentSelectionModel != null)
            {
                var equipmentRoster = Campaign.Current.Models.EquipmentSelectionModel
                    .GetEquipmentRostersForHeroReachesTeenAge(hero)
                    ?.GetRandomElementInefficiently<MBEquipmentRoster>();

                if (equipmentRoster != null)
                {
                    var civilianEquipments = equipmentRoster.GetCivilianEquipments();
                    if (civilianEquipments != null && civilianEquipments.Any())
                    {
                        var equipment = civilianEquipments.GetRandomElementInefficiently<Equipment>();
                        if (equipment != null)
                        {
                            EquipmentHelper.AssignHeroEquipmentFromEquipment(hero, equipment);
                            new Equipment(false).FillFrom(equipment, false);
                            EquipmentHelper.AssignHeroEquipmentFromEquipment(hero, equipment);
                        }
                        else
                        {
                            Debug.Print(
                                $"AgingCampaignBehavior.OnHeroReachesTeenAge: No valid equipment found for hero {hero.Name}.");
                        }
                    }
                    else
                    {
                        Debug.Print(
                            $"AgingCampaignBehavior.OnHeroReachesTeenAge: Civilian equipments are null or empty for hero {hero.Name}.");
                    }
                }
                else
                {
                    Debug.Print(
                        $"AgingCampaignBehavior.OnHeroReachesTeenAge: No equipment roster found for hero {hero.Name}.");
                }
            }
            else
            {
                Debug.Print("AgingCampaignBehavior.OnHeroReachesTeenAge: Campaign or EquipmentSelectionModel is null.");
            }
        }
        catch (System.Exception ex)
        {
            Debug.Print(
                $"AgingCampaignBehavior.OnHeroReachesTeenAge: Error in equipment assignment for hero {hero.Name}: {ex.Message}");
        }

        // Skip personality trait and developer initialization for player clan
        if (hero.Clan == Clan.PlayerClan)
        {
            return false; // Skip original method
        }

        // Handle personality traits safely
        try
        {
            if (DefaultTraits.Personality != null)
            {
                foreach (TraitObject trait in DefaultTraits.Personality)
                {
                    if (trait == null) continue;

                    int traitLevel = hero.GetTraitLevel(trait);
                    if (hero.Father == null && hero.Mother == null && hero.Template != null)
                    {
                        hero.SetTraitLevel(trait, hero.Template.GetTraitLevel(trait));
                    }
                    else
                    {
                        float randomFloat1 = MBRandom.RandomFloat;
                        float randomFloat2 = MBRandom.RandomFloat;

                        if (randomFloat1 < 0.2f && hero.Father != null)
                            traitLevel = hero.Father.GetTraitLevel(trait);
                        else if (randomFloat1 < 0.6f && hero.CharacterObject != null &&
                                 !hero.CharacterObject.IsFemale && hero.Father != null)
                            traitLevel = hero.Father.GetTraitLevel(trait);
                        else if (randomFloat1 < 0.6f && hero.Mother != null)
                            traitLevel = hero.Mother.GetTraitLevel(trait);
                        else if (randomFloat1 < 0.7f && hero.Mother != null)
                            traitLevel = hero.Mother.GetTraitLevel(trait);
                        else if (randomFloat2 < 0.3f)
                            traitLevel--;
                        else if (randomFloat2 >= 0.7f)
                            traitLevel++;

                        int clampedTraitLevel = MBMath.ClampInt(traitLevel, trait.MinValue, trait.MaxValue);
                        if (clampedTraitLevel != hero.GetTraitLevel(trait))
                            hero.SetTraitLevel(trait, clampedTraitLevel);
                    }
                }
            }
            else
            {
                Debug.Print("AgingCampaignBehavior.OnHeroReachesTeenAge: DefaultTraits.Personality is null or empty.");
            }
        }
        catch (System.Exception ex)
        {
            Debug.Print(
                $"AgingCampaignBehavior.OnHeroReachesTeenAge: Error in trait assignment for hero {hero.Name}: {ex.Message}");
        }

        // Initialize HeroDeveloper safely
        try
        {
            if (hero.HeroDeveloper != null)
            {
                hero.HeroDeveloper.InitializeHeroDeveloper(true);
            }
            else
            {
                Debug.Print($"AgingCampaignBehavior.OnHeroReachesTeenAge: HeroDeveloper is null for hero {hero.Name}.");
            }
        }
        catch (System.Exception ex)
        {
            Debug.Print(
                $"AgingCampaignBehavior.OnHeroReachesTeenAge: Error initializing HeroDeveloper for hero {hero.Name}: {ex.Message}");
        }

        return false; // Skip original method
    }
}